package com.ma.handler;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;

/**
 * @author 马永强
 */
//@ControllerAdvice它是一个Controller增强器,可对controller中被 @RequestMapping注解的方法加一些逻辑处理。
// 最常用的就是自定义异常处理

@ControllerAdvice
public class ControllerExceptionHandler {


    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    //统一异常处理 @ExceptionHandler 拦截所有异常

    @ExceptionHandler(Exception.class)
    public ModelAndView exceptionHandler(HttpServletRequest request,Exception e) throws Exception {

        logger.error("Request URL : {}, Exception : {}",request.getRequestURL(),e);

        //有状态码的异常，交还Spring处理
        if (AnnotationUtils.findAnnotation(e.getClass(), ResponseStatus.class)!=null){
            throw e;
        }

        //视图解析器，添加信息，返回错误页面
        ModelAndView mv = new ModelAndView();
        mv.addObject("url",request.getRequestURL());
        mv.addObject("exception",e);
        mv.setViewName("error/error");
        return  mv;

    }

}
